package com.im.utils.Redis;

import com.im.constant.RedisConstant;
import com.im.utils.Redis.RedisBatch.RedisScriptManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.ReturnType;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
public class RedisSequenceGenerator {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private OldRedisScriptManager redisScriptManager;//脚本管理器，lua脚本放里面了

    public Long getNextSequence(Long sessionId) {
        final String redisKey = RedisConstant.SESSION_MESSAGE_ID_PREFIX + sessionId;
        return redisTemplate.execute(new RedisCallback<Long>() {
            @Override
            public Long doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                byte[] keyBytes = serializer.serialize(redisKey);
                byte[] shaBytes = redisScriptManager.getScriptSha().getBytes(StandardCharsets.UTF_8);
                return (Long) connection.evalSha(shaBytes, ReturnType.INTEGER, 1, keyBytes);
            }
        }, true);
    }

}
